# -*- coding: utf-8 -*-
import re, os, traceback
from eqportal.qsync import models

class Quest:
    def __init__(self, name = None, type = None, level = None, repeatable = None, descr = None, pictures = None):
        self.name = name
        self.type = type
        self.level = level
        self.repeatable = repeatable
        self.pictures = pictures
        self.descr = descr
        self.locations = None
def QuestException (Exception):
    pass

class Location:
    def __init__(self, id = None, name = None):
        self.id = id
        self.name = name

_th_td_pair = re.compile('.*?<th\\s?.*?>\\s*(.*?):?\\s*</th>.*?<td\\s?.*?>\\s*(.*?)\\s*</td>(.*)', re.DOTALL)
_name_to_prop = {
	'Название': 'name',
	'Тип': 'type', 
        'Рекомендуемый уровень': 'level',
        'Повторяемый': 'repeatable',
        'Описание': 'descr',
        'Картинки': 'pictures',
        'Связанные зоны': 'locations'}

def _smth_from_html(ret, table_part):
    content = table_part
    match_result = _th_td_pair.match(content)
    while match_result:
        name = match_result.group(1)
        value = match_result.group(2)
        content = match_result.group(3)
        match_result = _th_td_pair.match(content)        
        #print name, _name_to_prop.get(name, 'aux')
        setattr(ret, _name_to_prop.get(name, 'aux'), value)
    return ret
def quest_from_html(table_part):
    return _smth_from_html(Quest(), table_part)
def location_from_html(table_part, id):
    return _smth_from_html(Location(id = id), table_part)

_table_regex = re.compile('.*?<table class="obj_prop">(.*?)</table>', re.DOTALL)
def _smth_from_file(filename, creator):
    f = open(filename)
    content = " ".join(f.readlines())
    match_object = _table_regex.match(content)
    if not match_object:
        raise QuestException("bad html")
    return creator(match_object.group(1))    
def quest_from_file(filename):
    return _smth_from_file(filename, quest_from_html)
def location_from_file(filename, id):
    return _smth_from_file(filename, lambda x: location_from_html(x, id))

def load_quests():
    quests = []
    for filename in os.listdir('quests'):
        try:
            quests.append(quest_from_file("quests/%s" % filename))
            print "completed %s" % filename        
        except:
            print filename, traceback.format_exc()
    return quests

def load_locations():
    locations = []
    for filename in os.listdir('locations'):
        try:
            locations.append(location_from_file("locations/%s" % filename, int(filename)))
            print "completed %s" % filename        
        except:
            print filename, traceback.format_exc()
    return locations

_loc_id_re = re.compile('id=(\\d+)')
def import_quests(quests):
    def _model_quest(quest):
        q_level = None;
        if quest.level:
            q_level = int(quest.level)
        q = models.Quest(name = quest.name, type = quest.type, level = q_level, descr = quest.descr)
        q.save()
        if quest.locations:
            [q.locations.add(int(loc_id)) for loc_id in _loc_id_re.findall(quest.locations)]
        return q
    [_model_quest(q) for q in quests]

def import_locations(locations):
    def _model_location(location):
        loc = models.Location(id = location.id, name = location.name)
        loc.save()
    [_model_location(l) for l in locations]
        

#import_quests(load_quests())
